package handler

import (
	"github.com/gin-gonic/gin"
	"store-mgmt/model"
	"strconv"
)

func ShopUp(c *gin.Context) {
	id := c.PostForm("id")
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	shop_name := c.PostForm("shop_name")
	shop_address := c.PostForm("shop_address")
	shop_content := c.PostForm("shop_content")
	err := model.DB.Model(&model.Shop{}).Where("id=?", id).Updates(map[string]interface{}{
		"Rid":         rid,
		"ShopName":    shop_name,
		"ShopAddress": shop_address,
		"ShopContent": shop_content,
	}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "修改失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "修改成功",
	})
	return

}

func ShopAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	shop_name := c.PostForm("shop_name")
	shop_address := c.PostForm("shop_address")
	shop_content := c.PostForm("shop_content")
	data := model.Shop{
		Rid:         rid,
		ShopName:    shop_name,
		ShopAddress: shop_address,
		ShopContent: shop_content,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "门店添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "门店添加成功",
	})
	return
}

func ShopList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var shop []model.Shop
	if err := model.DB.Offset(offset).Limit(size).Find(&shop).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "门店添加失败",
		})
		return
	}
	var total int64
	model.DB.Model(&shop).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "门店列表展示成功",
		"data":  shop,
		"total": total,
	})
	return
}
